<template>
	<view class="dplayer-container">
		<div ref="dplayer" id="dplayer"></div>
	</view>
</template>

<script>
	import DPlayer from 'dplayer';

	export default {
		data() {
			return {
				dp: null
			};
		},
		onReady() {
			this.dp = new DPlayer({
				container: document.getElementById('dplayer'),
				autoplay: false, // 尝试自动播放
				theme: '#FADFA3',
				loop: true,
				lang: 'zh-cn',
				// screenshot: true,
				hotkey: false,
				preload: 'auto',
				// logo: '/static/tabbar/home.png',
				volume: 0.7,
				mutex: true,
				video: {
					url: 'https://vjs.zencdn.net/v/oceans.mp4',
					// pic: '/static/tabbar/home.png',
					thumbnails: 'thumbnails.jpg',
					type: 'auto',
				},
			});
			// 手动开始播放视频
			// this.startVideo();

			// 隐藏默认的全屏按钮
			const fullscreenButton = this.$refs.dplayer.querySelector('.dplayer-full-in-icon');
			if (fullscreenButton) {
				fullscreenButton.style.display = 'none';
			}
			// 监听事件，例如全屏事件
			this.dp.on('fullscreen', this.handleFullscreenChange);
			this.dp.on('fullscreen_cancel', this.handleFullscreenChange);

			this.$nextTick(() => {
				if (this.dp) {
					this.startVideo();
				}
			})
		},
		
		onUnload() {
			// 在组件销毁前销毁 DPlayer 实例
			if (this.dp) {
				this.dp.destroy();
			}
		},
		methods: {
			startVideo() {
				// 尝试播放视频
				const promise = this.dp.play();
				if (promise !== undefined) {
					promise.then(() => {
						// 播放成功
						console.log('视频自动播放成功');
					}).catch(error => {
						// 播放失败，可能需要用户交互触发
						console.error('视频自动播放失败:', error);
					});
				}
			},
			handleFullscreenChange() {
				const isLandscape = window.innerWidth > window.innerHeight;
				if (!isLandscape) {
					this.dp.fullScreen.cancel('browser'); // 退出全屏
				}
			},
			handleOrientationChange() {
				const isLandscape = window.innerWidth > window.innerHeight;
				if (!isLandscape && this.dp.fullScreen.isFullScreen('browser')) {
					this.dp.fullScreen.cancel('browser'); // 退出全屏
				}
			}
		},
	}
</script>

<style scoped>
	.dplayer-container {
		/* margin-top: 100px; */
		width: 100%;
		height: 500px;

		.dplayer {
			height: 260px;
		}
	}
</style>